package com.lm.iotdb.service;

import com.lm.iotdb.component.UploadProgressCache;
import com.lm.iotdb.entry.DeviceDataDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

@Service
public class IoTDataService {

    @Autowired
    private Connection connection;

    @Autowired
    private UploadProgressCache cache;

    public boolean save(DeviceDataDTO dto) {
        long lastTimestamp = cache.getLastTimestamp(dto.getDeviceId());

        if (dto.getTimestamp() <= lastTimestamp) {
            return false; // 重复数据，不再插入
        }

        String sql = String.format("INSERT INTO root.device.%s(timestamp, temperature, humidity) VALUES(%d, %f, %f)",
                dto.getDeviceId(), dto.getTimestamp(), dto.getTemperature(), dto.getHumidity());

        try (Statement stmt = connection.createStatement()) {
            stmt.execute(sql);
            cache.updateTimestamp(dto.getDeviceId(), dto.getTimestamp());
            return true;
        } catch (SQLException e) {
            throw new RuntimeException("IoTDB 插入失败", e);
        }
    }
}
